package com.camera2.frament;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.camera2.activity.ExpertMessageDetail;
import com.camera2.activity.R;
import com.camera2.adapter.MessageAdapter;
import com.camera2.adapter.SetListViewHeight;
import com.camera2.bean.ApplicationHelper;
import com.camera2.bean.MessageBean;
import com.camera2.http.GetMessage;
import com.camera2.local.SharedPrefer;

import java.util.ArrayList;
import java.util.List;


public class ExpertMessage extends Fragment implements ViewPager.OnPageChangeListener, SwipeRefreshLayout.OnRefreshListener {
    private final static String TAG = "FramentMessage";

    private LinearLayout llPoints;
    private int previousSelectPosition = 0;
    private ViewPager mViewPager;
    private List<ImageView> imageViewList;
    private View view;


    private boolean isLoop = true;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
        }
    };
    private Handler handler1 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mSwipeLayout.setRefreshing(false);
            initEvent();

        }
    };


    private ListView lv;
    private SwipeRefreshLayout mSwipeLayout;
    private MessageAdapter adapter;
    private String id;
    private List<MessageBean> list;

    private int page;
    private Button bt_warn_next;
    private Button bt_warn_up;


    @Override
    public View onCreateView(android.view.LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frament_expert_message, null);
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        mViewPager = view.findViewById(R.id.user_viewpager);
        llPoints = view.findViewById(R.id.ll_user_points);
        mSwipeLayout = view.findViewById(R.id.swipe_warn_list);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setOnRefreshListener(this);
        lv = view.findViewById(R.id.lv_expert_list);
        bt_warn_next = view.findViewById(R.id.bt_warn_next);
        bt_warn_up = view.findViewById(R.id.bt_warn_up);
        bt_warn_up.setVisibility(View.GONE);
        bt_warn_next.setVisibility(View.GONE);

        initView();
        GetMessage();
        return view;

    }

    public void initEvent() {

        mSwipeLayout.setRefreshing(false);
        list = ((ApplicationHelper) getActivity().getApplicationContext()).getMessageBeanList();

        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Log.i(TAG, "initEvent: " + i);
                Log.i(TAG, "initEvent: "+list.get(i).getExpertId()+"---"+SharedPrefer.Readid(getContext()));
                if (!list.get(i).getExpertId().equals(SharedPrefer.Readid(getContext()))) {
                    list.remove(list.get(i));
                    i = i - 1;
                    Log.i(TAG, "list.remove(i);: " + i + "---" + list.size());
                }
            }
            if (list.size() > 10) {
                bt_warn_up.setVisibility(View.VISIBLE);
                bt_warn_next.setVisibility(View.VISIBLE);
            }
            adapter = new MessageAdapter(getActivity(), list);
            lv.setAdapter(adapter);
            SetListViewHeight.setListViewHeightBasedOnChildren(lv);
//            Log.i(TAG, "initEvent: " + list);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id1) {
                    switch (position) {
                        default: {
                            ((ApplicationHelper) getActivity().getApplicationContext()).setMessageBean(list.get(position));
                            Intent intent = new Intent(getActivity(), ExpertMessageDetail.class);
                            startActivity(intent);
                            break;
                        }
                    }
                }
            });
        } else {
            Toast.makeText(getContext(), "没有留言信息", Toast.LENGTH_SHORT).show();
        }

    }


    public void onRefresh() {
        GetMessage();
        mSwipeLayout.setRefreshing(true);

    }


    public void GetMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String log = GetMessage.get(getActivity());
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = log;
                    handler1.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 0;
                    handler1.sendMessage(msg);
                }

            }
        }).start();
    }


    public void initView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLoop) {
                    SystemClock.sleep(3 * 1000);
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();

        prepareData();
        ViewPagerAdapter adapter = new ViewPagerAdapter();
        mViewPager.setAdapter(adapter);

        mViewPager.setOnPageChangeListener(this);
        llPoints.getChildAt(previousSelectPosition).setEnabled(true);
        int n = Integer.MAX_VALUE / 2 % imageViewList.size();
        int itemPosition = Integer.MAX_VALUE / 2 - n;
        mViewPager.setCurrentItem(itemPosition);
    }

    private void prepareData() {
        imageViewList = new ArrayList<ImageView>();
        int[] imageResIDs = getImageResIDs();
        ImageView iv;
        View view;
        for (int i = 0; i < imageResIDs.length; i++) {
            iv = new ImageView(getActivity());
            iv.setBackgroundResource(imageResIDs[i]);
            imageViewList.add(iv);
            view = new View(getActivity());

            view.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.point_background));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(3, 3);
            lp.leftMargin = 20;
            lp.height = 20;
            lp.width = 20;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            llPoints.addView(view);
        }
    }

    private int[] getImageResIDs() {
        return new int[]{R.drawable.guanggao1, R.drawable.guanggao2,
                R.drawable.guanggao3,};
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViewList.get(position
                    % imageViewList.size()));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            try {
                container.addView(imageViewList.get(position
                        % imageViewList.size()));
                return imageViewList.get(position % imageViewList.size());
            } catch (Exception e) {
                e.printStackTrace();
                return true;
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        llPoints.getChildAt(previousSelectPosition).setEnabled(false);
        llPoints.getChildAt(position % imageViewList.size()).setEnabled(true);
        previousSelectPosition = position % imageViewList.size();
    }
}
